import {
  DrawerForm,
  ProForm,
  ProFormCheckbox,
  ProFormInstance,
  ProFormList,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-components';
import { Input, message, Space, Tabs } from 'antd';
const { Search } = Input;
import React, { useEffect, useRef, useState } from 'react';
import { dyCpsSearchStore, getStoreCate, getStoreList } from '../service';

export type FormValueType = {
  target?: string;
  template?: string;
  type?: string;
  time?: string;
  frequency?: string;
} & Partial<API.RuleListItem>;

export type UpdateFormProps = {
  onCancel: (flag?: boolean, formVals?: FormValueType) => void;
  onSubmit: (values: FormValueType) => Promise<void>;
  updateModalVisible: boolean;
  values: Partial<API.RuleListItem>;
};

const EditCateForm: React.FC<UpdateFormProps> = (props) => {
  const formRef = useRef<ProFormInstance>();
  const [form] = ProForm.useForm();
  const fetchData = async () => {
    try {
      const rsp = await getStoreList();
      const data = rsp.data;
      
      // 转换接口数据为 ProFormList 需要的格式（添加 checked 字段）
      const initialItems = data.map(item => ({ 
        checked: false, // 默认未勾选
        store: item.name,
        text: item.dname,
        id: item.id
      }));
      
      form.setFieldsValue({ items: initialItems }); // 设置表单初始值
    } catch (error) {
      message.error('数据加载失败');
    } finally {
    }
  };

  useEffect(() => {
    fetchData();
  }, []);
  return (
    <DrawerForm
      title="处理分类"
      width="620px"
      formRef={formRef}
      form={form}
      visible={props.updateModalVisible}
      onVisibleChange={(val) => {
        if (!val) {
          props.onCancel();
        }
       
      }}
      onFinish={async (values) => {
        const { items = [] } = values;
        const selectedItems = items
          .filter((item: { checked: boolean; id?: number }) => item.checked && item.id)
          .map((item: { id: string }) => item);
        props.onSubmit({list: selectedItems,cate: values.cate});
      }}
    >
      <ProFormSelect
        name="cate"
        width="md"
        label="店铺选择"
        request={async () => {
          const rsp = await getStoreCate();
          return rsp.data;
        }}
        placeholder="请选择店铺"
        rules={[{ required: true, message: 'Please select your country!' }]}
      /> 
      <ProFormList
        name="items"
        itemContainerRender={(doms) => <div style={{ marginBottom: 16 }}>{doms}</div>}
      >
        {(field, index, action) => (
          <ProForm.Group>
            <ProFormCheckbox name="checked"/>
            <ProFormText width="sm" name="text" placeholder="内容"  rules={[{ required: true }]} />
            <ProFormText width="sm" name="store" placeholder="内容"  rules={[{ required: true }]} />
          </ProForm.Group>
        )}
      </ProFormList>
    </DrawerForm>
  );
};

export default EditCateForm;
